package com.eaero.util;

import cn.hutool.core.codec.Base64;
import org.springframework.beans.factory.annotation.Value;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author luofeng
 * @create 2023/3/1 16:54
 */
public class SM4Utils {

    /**
     * 密钥
     */
    @Value("${cipher.sm4.key:}")
    private static String secretKey = "!1qw2@#3ER4$%5ty";

    /**
     * 向量
     */
    @Value("${cipher.sm4.iv:}")
    private static String iv = "*&^0p9O8i7U6MnBv";

    /**
     * cbc加密
     * @param plainText
     * @return
     */
    public static String encryptData_CBC(String plainText) {
        try {
            SM4Context ctx = new SM4Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;

            byte[] keyBytes = secretKey.getBytes();
            byte[] ivBytes = iv.getBytes();

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes("UTF-8"));
            String cipherText = Base64.encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
